<template>
  <div>
    <!-- 面包屑导航 -->
    <Breadcrumb />
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        :closable="false"
        type="info"
        center
        show-icon
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input
                v-model="addForm.goods_name"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addForm.goods_price"
                placeholder="请输入商品价格"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addForm.goods_weight"
                placeholder="请输入商品重量"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addForm.goods_number"
                placeholder="请输入商品数量"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="categories"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑框 -->
            <quill-editor
              ref="myQuillEditor"
              v-model="addForm.goods_introduce"
            />
            <!-- 添加商品按钮 -->
            <el-button type="primary" style="margin-top: 20px" @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 图片预览 -->
      <el-dialog title="预览" :visible.sync="previewVisible" width="50%">
        <img :src="previewUrl" style="width: 100%; height: 100%" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  name: "add",
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        //商品所属分类数组
        goods_cat: [],
        //图片数组
        pics: [],
        //商品详情
        goods_introduce: "",
        //属性列表
        attrs: [],
      },
      //商品分类数据列表
      categories: [],
      addFormrules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [{ required: true, message: "请选择分类", trigger: "blur" }],
      },
      //级联选择框配置
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      //动态参数
      manyTableData: [],
      //静态参数
      onlyTableData: [],
      //图片上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      //控制图片预览框显示与隐藏
      previewVisible: false,
      //图片预览路径
      previewUrl: "",
    };
  },
  methods: {
    async getCateList() {
      const res = await this.$http.getCategories();
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类数据列表失败");
      }
      this.categories = res.data;
    },
    //级联选择项变化
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    //离开上一个tab函数
    beforeTabLeave(activename, oldactivename) {
      if (oldactivename === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    //tab切换
    async tabClick() {
      //证明访问的是动态参数列表
      if (this.activeIndex === "1") {
        const res = await this.$http.getCateInfo(this.cateId, {
          params: { sel: "many" },
        });
        if (res.meta.status !== 200) {
          return this.$message.error("获取动态参数失败");
        }
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTableData = res.data;
      }
      if (this.activeIndex === "2") {
        const res = await this.$http.getCateInfo(this.cateId, {
          params: { sel: "only" },
        });
        if (res.meta.status !== 200) {
          return this.$message.error("获取静态参数失败");
        }
        this.onlyTableData = res.data;
      }
      if (this.activeIndex === "3") {
        //处理动态参数
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        //处理静态属性
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(newInfo);
        });
      }
    },
    //预览图片
    handlePreview(r) {
      this.previewUrl = r.response.data.url;
      this.previewVisible = true;
    },
    //移除图片
    handleRemove(file) {
      const r = file.response.data.tmp_path;
      //找到索引
      const i = this.addForm.pics.findIndex((x) => x.pic == r);
      //移除图片
      this.addForm.pics.splice(i, 1);
    },
    //上传图片成功回调
    handleSuccess(response) {
      const picInfo = {
        pic: response.data.tmp_path,
      };
      this.addForm.pics.push(picInfo);
    },
    //添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const form = _.cloneDeep(this.addForm);
          form.goods_cat = form.goods_cat.join(",");
          console.log(form);
          const res = await this.$http.addGoods(form);
          if (res.meta.status !== 201) {
            return this.$message.error("添加商品失败");
          }
          this.$message.success("添加成功");
          this.$router.push("/hgoods/goods");
        } else {
          this.$message.error("请填写必要的表单项");
          return false;
        }
      });
    },
  },
  created() {
    this.getCateList();
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 20px;
}
.el-step_title {
  font-size: 12px;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
</style>
